import React, { Component } from 'react';

class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      msg: "",
      list: [],
      listing: 0,
      listed: 0
    }
  }
  render() {
    const ListItem = this.state.list.map((item, index) => {
      if (item.check === false) {
        return (
          <div key={item.id} >
            <input type="checkbox" name="" id="" onChange={this.toDo.bind(this, index)} /> {item.msg}
            <button onClick={this.handleDelete.bind(this, index)}>删除</button>
          </div>
        )
      }
    })
    const DoneItem = this.state.list.map((item, index) => {
      if (item.check === true) {
        return (
          <div key={item.id}>
            <input type="checkbox" name="" id="" checked={item.check} onChange={this.toDo.bind(this, index)} /> {item.msg}
            <button onClick={this.handleDelete.bind(this, index)}>删除</button>
          </div>
        )
      }
    })
    return (
      <div>
        <h1>TodoList</h1>
        <input type="text" onChange={this.handleChange} value={this.state.msg} onKeyUp={this.handleEnter} />
        <h2>进行中 {this.state.listing}</h2>
        {ListItem}
        <h2>已完成 {this.state.listed}</h2>
        {DoneItem}
      </div>
    );
  }
  //页面初次加载，获取缓存
  componentDidMount() {
    var list = this.state.list;
    var listing = this.state.listing;
    var listed = this.state.listed;
    list = JSON.parse(localStorage.getItem("key"))||[];
    listing = JSON.parse(localStorage.getItem("listing"))||0;
    listed = JSON.parse(localStorage.getItem("listed"))||0;
    this.setState({ list, listing, listed })
  }
  handleChange = (event) => {
    this.setState({ msg: event.target.value })
  }

  //回车添加数据
  handleEnter = (event) => {
    if (event.keyCode === 13) {
      var obj = {
        msg: this.state.msg,
        check: false,
        id: Math.random()
      }
      var list = this.state.list
      var s = list.findIndex(item => item.msg === obj.msg);
      if (s === -1) {
        list.push(obj);
        this.setState({ list, msg: "" })
       
      }
      this.setlocal()
    }
  }
  // 点击切换 进行中 = 已完成
  toDo = (index) => {
    var list = this.state.list;
    list[index].check = !list[index].check
    this.setState({
          list
    })
    this.setlocal()
    
  }

  //点击删除
  handleDelete(e) {
    var list = this.state.list;
    list.splice(e, 1)
  
    this.setState({ list })
    this.setlocal()
  }

  //设置缓存，实现数据持久化
  setlocal() {
    var list = this.state.list;
    var listing = 0;
    var listed = 0;
    //获取数组 进行中 和 已完成 的长度
    list.forEach(item => {
      if (item.check === false) {
        listing++
      } else {
        listed++
      }
    })
    this.setState({
      listing,
      listed
    })
    localStorage.setItem("key", JSON.stringify(this.state.list))
    localStorage.setItem("listing", JSON.stringify(listing))
    localStorage.setItem("listed", JSON.stringify(listed))
    
  }
}

export default Index;
